package pers.xhh.shopapi.exception.handler;


import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import pers.xhh.shopapi.common.Mi;
import pers.xhh.shopapi.common.ResultCode;
import pers.xhh.shopapi.exception.MiException;
import pers.xhh.shopapi.util.LogUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 统一异常返回类
 * @author wei-xhh
 * @date 2020-11-22
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 指定出现什么异常执行这个方法
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Mi error(Exception e){
        e.printStackTrace();
        return Mi.error(ResultCode.ERROR500.getMessage(), ResultCode.ERROR500.getStatus());
    }


    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(MiException.class)
    public Mi error(MiException e){
        LogUtils.logError(MiException.class, e.getMsg());
        return Mi.error(e.getMsg(),e.getStatus());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Mi handleVaildException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return Mi.ok("数据校验出现问题", 700, errorMap);
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Mi handleServletRequestParameter(MissingServletRequestParameterException e){
        LogUtils.logError(MissingServletRequestParameterException.class, "参数不合法");
        return Mi.error("参数不合法", 700);
    }
}
